/**
 * 身份证校验
 *
 * @param
 * @returns
 */
// 身份证号码校验函数
export function validateIdCard(rule: any, value: string, callback: any) {
  if (!value) {
    // return callback(new Error("身份证号码不能为空"));
    return callback();
  }
  if (!/^\d{17}[\dX]$/.test(value)) {
    return callback(new Error("请输入正确的身份证号码格式"));
  }
  if (!isValidIdCard(value)) {
    return callback(new Error("身份证号码无效"));
  }
  callback();
}

// 校验身份证号码的逻辑
function isValidIdCard(idCard: string | number) {
  const coefficients = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checksumMap = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
  const sum = idCard
    .toString()
    .slice(0, 17)
    .split("")
    .reduce(
      (acc: number, num: string, index: number) => acc + parseInt(num) * coefficients[index],
      0
    );
  const checksumIndex = sum % 11;
  const expectedChecksum = checksumMap[checksumIndex];
  const actualChecksum = idCard.toString().slice(17);

  return expectedChecksum === actualChecksum;
}

/**
 * 手机号校验
 *
 * @param
 * @returns
 */
export function validatePhone(rule: any, value: string, callback: any) {
  if (!value) {
    callback(new Error("手机号不能为空"));
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
}
